//
//  TLCollectionListViewController.m
//  WXReader
//
//  Created by huaya on 2025/3/29.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLCollectionListViewController.h"
#import "HMSegmentedControl.h"
#import "TLCollectionListCollectionViewCell.h"
#import "TLHistoryListTableViewCell.h"
#import "TLAlterView.h"

@interface TLCollectionListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) HMSegmentedControl *segControl;
@property (nonatomic, strong) UIButton *editBtn;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *editDataArr;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *dataArrForHis;

@property (nonatomic, strong) NSNumber *pageNumb;
@property (nonatomic, strong) NSNumber *pageSize;
@property (nonatomic, strong) NSNumber *pageNumbForHis;
@property (nonatomic, strong) NSNumber *pageSizeForHis;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *editView;
@property (nonatomic, strong) UIButton *allSelectedBtn;
@property (nonatomic, strong) UIButton *deleteBtn;

@property (nonatomic, assign) BOOL allEdit;

@end

@implementation TLCollectionListViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
    if (TL_UserInfoManager.isLogin) {
        
        if (_segControl.selectedSegmentIndex==0) {
            [self.collectionView.mj_header beginRefreshing];
        }else{
            [self.tableView.mj_header beginRefreshing];
        }
    }
    
}
- (NSMutableArray *)editDataArr{
    if (!_editDataArr) {
        _editDataArr = [NSMutableArray new];
    }
    return _editDataArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view removeAllSubviews];
    self.allEdit = NO;
    self.pageNumb = [NSNumber numberWithInt:1];
    self.pageSize = [NSNumber numberWithInt:20];
    
    self.pageNumbForHis = [NSNumber numberWithInt:1];
    self.pageSizeForHis = [NSNumber numberWithInt:20];
    
    [self setupUI];
    
    [self netWork];
}

- (void)setupUI{
    [self.view addGradientBackground];
    [self.view addSubview:self.segControl];
    [self.segControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(16);
        make.top.equalTo(self.view.mas_top).offset(kStatusBarHeight+18);
        make.height.mas_offset(30);
        make.width.mas_offset(200);
    }];
    [self.view addSubview:self.editBtn];
    [self.editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-16);
        make.centerY.equalTo(self.segControl.mas_centerY);
        make.height.mas_offset(22);
        make.width.mas_offset(22);
    }];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.segControl.mas_bottom).mas_offset(10);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.segControl.mas_bottom).mas_offset(10);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.view addSubview:self.editView];
    self.editView.hidden = YES;
    [self.editView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(self.view);
        make.height.mas_offset(54);
        make.bottom.equalTo(self.view.mas_bottom);
        
    }];
    [self.editView layoutIfNeeded];
    
}
- (UIView *)editView{
    if (!_editView) {
        _editView = [[UIView alloc] init];
        [_editView setBackgroundColor:[UIColor whiteColor]];
        
        self.allSelectedBtn = [[UIButton alloc] init];
        [self.allSelectedBtn setTitle:@"Select all" forState:UIControlStateNormal];
        self.allSelectedBtn.titleLabel.font = SYSTEM_FONT(14);
        [_allSelectedBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
        [_allSelectedBtn addTarget:self action:@selector(allSelectedAction) forControlEvents:UIControlEventTouchUpInside];
        [_editView addSubview:self.allSelectedBtn];
        [self.allSelectedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.left.equalTo(_editView);
            make.width.mas_offset(kScreenWidth/2);
        }];
        
        self.deleteBtn = [[UIButton alloc] init];
        [self.deleteBtn setTitle:@"Delete" forState:UIControlStateNormal];
        self.deleteBtn.titleLabel.font = SYSTEM_FONT(14);
        [_deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
        [_deleteBtn setTitleColor:kMainColor forState:UIControlStateNormal];
        [_editView addSubview:self.deleteBtn];
        [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(_editView);
            make.left.equalTo(_allSelectedBtn.mas_right);
            make.width.mas_offset(kScreenWidth/2);
        }];
        
    }
    return _editView;
}
- (void)allSelectedAction{
    
    self.allEdit = !self.allEdit;
    
    [self.editDataArr removeAllObjects];
    
    for (TL_ProductionModel *model in self.dataArr) {
        [self.editDataArr addObject:[NSNumber numberWithInteger:model.production_id]];
    }
    
    if (!_allEdit) {
        [self.editDataArr removeAllObjects];
    }
    
    NSString *titleStr = @"Delete";
    
    if (self.editDataArr.count>0){
        titleStr = [NSString stringWithFormat:@"Delete(%ld)",self.editDataArr.count];
    }
    
    [self.deleteBtn setTitle:titleStr forState:UIControlStateNormal];
    
    [self.collectionView reloadData];
    
}
- (void)deleteAction{
    
    [APIManager sendPostRequest:[APIURLManager delCollectList] parameters:@{@"worksIds":self.editDataArr} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            [self.collectionView.mj_header beginRefreshing];
            
            [self editAction];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
}
- (void)editAction{
    
    if (self.segControl.selectedSegmentIndex == 0) {
        
        self.editBtn.selected = !self.editBtn.selected;
        
        if (self.editBtn.selected) {
            
            self.segControl.userInteractionEnabled = NO;
            [self.editBtn setTitle:@"Cancel" forState:UIControlStateNormal];
            [self.editBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
            self.editBtn.titleLabel.font = MK_FONT_PFSC_Medium(16);
            
            [self.editBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            
            [self.editBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.view.mas_right).offset(-16);
                make.centerY.equalTo(self.segControl.mas_centerY);
                make.height.mas_offset(22);
                make.width.mas_offset(62);
            }];
            
            self.editView.hidden = NO;
            
            [self.deleteBtn setTitle:@"Delete" forState:UIControlStateNormal];
            
            [self.editDataArr removeAllObjects];
            
        }else{
            [self.editDataArr removeAllObjects];
            self.allEdit = NO;
            self.segControl.userInteractionEnabled = YES;
            [self.editBtn setTitle:@"" forState:UIControlStateNormal];
            [self.editBtn setImage:[UIImage imageNamed:@"edit-collect"] forState:UIControlStateNormal];
            [self.editBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.view.mas_right).offset(-16);
                make.centerY.equalTo(self.segControl.mas_centerY);
                make.height.mas_offset(22);
                make.width.mas_offset(22);
            }];
            self.editView.hidden = YES;
            
        }
        [self.collectionView reloadData];
        
    }else{
        TLAlterView *alterView = [TLAlterView createView];
        [alterView showActionWithTitle:@"All records will be permanently deleted and cannot be recovered." andLeftBtnTitle:@"Cancel" andRightBtnTitle:@"Clear"];
        
        alterView.rightBtnBlock = ^{
            
            [self clearHis];
            
        };
    }
}
- (UIButton *)editBtn{
    if (!_editBtn) {
        _editBtn = [[UIButton alloc] init];
        
        [_editBtn setImage:[UIImage imageNamed:@"edit-collect"] forState:UIControlStateNormal];
        
        [_editBtn addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editBtn;
}
- (HMSegmentedControl *)segControl{
    if (!_segControl) {
        _segControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Library",@"History"]];
        _segControl.backgroundColor = UIColor.clearColor;
        _segControl.titleTextAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:16],
                                            NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#333333"]};
        _segControl.selectedTitleTextAttributes = @{NSFontAttributeName : MK_FONT_PFSC_Medium(16),
                                                    NSForegroundColorAttributeName : [UIColor blackColor]};
        
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationNone;
        _segControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
        
        _segControl.selectionIndicatorHeight = 3.0f;
        _segControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segControl.selectionIndicatorColor = kMainColor;
        
        _segControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
        
        MJWeakSelf
        _segControl.indexChangeBlock = ^(NSInteger index) {
            if (index==0) {
                weakSelf.collectionView.hidden = NO;
                weakSelf.tableView.hidden = YES;
                if (weakSelf.dataArr.count==0) {
                    [weakSelf.collectionView.mj_header beginRefreshing];
                }
                
                [weakSelf.editBtn setImage:[UIImage imageNamed:@"edit-collect"] forState:UIControlStateNormal];
                
            }else{
                weakSelf.collectionView.hidden = YES;
                weakSelf.tableView.hidden = NO;
                if (weakSelf.dataArrForHis.count==0) {
                    [weakSelf.tableView.mj_header beginRefreshing];
                }
                [weakSelf.editBtn setImage:[UIImage imageNamed:@"trash-his"] forState:UIControlStateNormal];
            }
        };
        
    }
    return _segControl;
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}
- (NSMutableArray *)dataArrForHis{
    if (!_dataArrForHis) {
        _dataArrForHis = [NSMutableArray new];
    }
    return _dataArrForHis;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        // 创建 UICollectionViewFlowLayout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        // 设置两列，行间距和列间距
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        layout.itemSize = CGSizeMake((screenWidth - 15 * 2 - 9*2) / 3, 190);
        layout.minimumLineSpacing = 24; // 行间距
        layout.minimumInteritemSpacing = 9; // 列间距
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15); // 左右边距17
        layout.sectionHeadersPinToVisibleBounds = NO;
        // 初始化 UICollectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.scrollEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        // 注册 NIB 文件
        [_collectionView registerNib:[UINib nibWithNibName:@"TLCollectionListCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TLCollectionListCollectionViewCell"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _collectionView.mj_header = header;
        
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _collectionView.mj_footer.hidden = YES;
        
    }
    return _collectionView;
}
- (void)loadLastData{
    if (_segControl.selectedSegmentIndex == 0) {
        self.pageNumb = @(1);
        [self.dataArr removeAllObjects];
    }else{
        self.pageNumbForHis = @(1);
        [self.dataArrForHis removeAllObjects];
    }
    
    [self netWork];
    
}
- (void)loadMoreData{
    
    if (_segControl.selectedSegmentIndex == 0) {
        
        self.pageNumb = [NSNumber numberWithInt:(self.pageNumb.intValue+1)];
    }else{
        
        self.pageNumbForHis = [NSNumber numberWithInt:(self.pageNumbForHis.intValue+1)];
    }
    [self netWork];
    
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TLCollectionListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TLCollectionListCollectionViewCell" forIndexPath:indexPath];
    
    cell.dataModel = self.dataArr[indexPath.row];
    
    cell.isAllSelected = self.allEdit;
    
    cell.isEidt = self.editBtn.selected;
    
    cell.selectedBlock = ^(NSInteger index) {
        // 检查数组中是否存在 @1
        BOOL containsOne = [self.editDataArr containsObject:@(index)];
        if (containsOne) {
            // 删除所有值为 @1 的元素
            [self.editDataArr removeObject:@(index)];
        } else {
            // 不存在则添加一个 @1
            [self.editDataArr addObject:@(index)];
        }
        
        NSString *titleStr = @"Delete";
        
        if (self.editDataArr.count>0){
            titleStr = [NSString stringWithFormat:@"Delete(%ld)",self.editDataArr.count];
        }
        
        [self.deleteBtn setTitle:titleStr forState:UIControlStateNormal];
        
    };
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.editBtn.selected) {
        return;
    }
    
    TL_ProductionModel *model = self.dataArr[indexPath.row];
    
    if ([model.worksType isEqualToString:@"0"]) {
        //短篇
        TLShortStoryViewController *vc = [TLShortStoryViewController new];
        vc.worksId = [NSString stringWithFormat:@"%ld",model.production_id];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        //长篇
//        TL_BookReaderViewController *vc = [[TL_BookReaderViewController alloc] init];
//        vc.book_id = model.production_id;
//        [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:vc animated:YES];
//        [[TL_ProductionCollectionManager shareManagerWithProductionType:TL_ProductionTypeBook] moveCollectionToTopWithProductionModel:model];
    }
    
}
- (void)netWork{
    if (_segControl.selectedSegmentIndex==0) {
        [self getCollectListNetWork];
    }else{
        [self getHistoryListNetWork];
    }
}
- (void)getHistoryListNetWork{
    
    NSDictionary *param = @{
        @"pageNum":self.pageNumbForHis,
        @"pageSize":self.pageSizeForHis,
    };
    
    [APIManager sendGetRequest:[APIURLManager getHistoryList] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            NSArray *dataArr = [TL_ProductionModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"records"]];
            
            [self.dataArrForHis addObjectsFromArray:dataArr];
            
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            
            if (dataArr.count<self.pageSizeForHis.intValue) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
            if (dataArr.count==0) {
                
                [self setEmptyOnView:self.tableView title:WXLocalizedString(@"暂无历史记录") buttonTitle:@"" tapBlock:^{
                    
                }];
                [self.tableView ly_showEmptyView];
            }else{
                [self.tableView ly_hideEmptyView];
            }
        }
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self.tableView.mj_header endRefreshing];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}
- (void)getCollectListNetWork{
    
    NSDictionary *param = @{
        @"pageNum":self.pageNumb,
        @"pageSize":self.pageSize,
        
    };
    
    [APIManager sendGetRequest:[APIURLManager getCollectList] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            NSArray *dataArr = [TL_ProductionModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"records"]];
            
            [self.dataArr addObjectsFromArray:dataArr];
            
            [self.collectionView reloadData];
            
            [self.collectionView.mj_header endRefreshing];
            
            if (dataArr.count<self.pageSize.intValue) {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.collectionView.mj_footer endRefreshing];
            }
            
            if (dataArr.count==0) {
                
                [self setEmptyOnView:self.collectionView title:WXLocalizedString(@"暂无数据") buttonTitle:@"" tapBlock:^{
                    
                }];
                [self.collectionView ly_showEmptyView];
            }else{
                [self.collectionView ly_hideEmptyView];
            }
        }else{
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
}

- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;

        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.mj_footer.hidden = YES;
        
        [_tableView registerNib:[UINib nibWithNibName:@"TLHistoryListTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLHistoryListTableViewCell"];
        
    }
    return _tableView;
}
#pragma mark - table delegate - datasource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TLHistoryListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLHistoryListTableViewCell"];
    
    cell.dataModel = self.dataArrForHis[indexPath.row];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.segControl.selectedSegmentIndex == 0) {
        return 0;
    }else{
        return self.dataArrForHis.count;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    TL_ProductionModel *model = self.dataArrForHis[indexPath.row];
    
    if ([model.worksType isEqualToString:@"0"]) {
        //短篇
        TLShortStoryViewController *vc = [TLShortStoryViewController new];
        vc.worksId = [NSString stringWithFormat:@"%ld",model.production_id];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        //长篇
//        TL_BookMallDetailViewController *vc = [TL_BookMallDetailViewController new];
//        vc.book_id = model.production_id;
//        [self.navigationController pushViewController:vc animated:YES];
        
//        TL_BookReaderViewController *vc = [[TL_BookReaderViewController alloc] init];
//        vc.book_id = model.production_id;
//        [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:vc animated:YES];
//        [[TL_ProductionCollectionManager shareManagerWithProductionType:TL_ProductionTypeBook] moveCollectionToTopWithProductionModel:model];
        
    }
    
    
}
- (void)clearHis{
    
    NSDictionary *param = @{
        @"pageNum":self.pageNumb,
        @"pageSize":self.pageSize,
    };
    
    
    [APIManager sendPostRequest:[APIURLManager getHistoryList] parameters:@{@"worksIds":self.editDataArr} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            [self.dataArrForHis removeAllObjects];
            
            self.pageNumb = @(0);
            
            [self.tableView reloadData];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
}
@end
